package edu.gyc.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class MyCounter {
    public static int count = 0;

    static AtomicInteger atomic = new AtomicInteger(0);

    public  static void inc() {

        //这里延迟1毫秒，使得结果明显
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }

        count++;
    }

    public  static void safeInc() {

        //这里延迟1毫秒，使得结果明显
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
        }

        atomic.incrementAndGet();

    }

    public static void main(String[] args) throws InterruptedException {

        for (int j = 0; j < 30; j++) {
           CountDownLatch countDownLatch = new CountDownLatch(2000);
            //同时启动1000个线程，去进行i++计算，看看实际结果

            for (int i = 0; i < 1000; i++) {
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        MyCounter.inc();
                        countDownLatch.countDown();
                      //  MyCounter.safeInc();


                    }
                });
                thread.start();

              //  thread.join(); //join 就是synchronize，阻塞线程，也能确保计数正常进行，但是效率低下

            }


            for (int i = 0; i < 1000; i++) {
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                      //  MyCounter.inc();
                        MyCounter.safeInc();

                   countDownLatch.countDown();
                    }
                });
                thread.start();
              //  thread.join();


            }

/*
            try {
                Thread.sleep(2000);//这个值要保证前面的计算线程结束了，再取值才有意义
            } catch (InterruptedException e) {
            }
*/
           countDownLatch.await();
            //这里每次运行的值都有可能不同,可能为1000
            System.out.println("运行结果:Counter.count=" + MyCounter.count);
            System.out.println("运行结果:atomic.count=" + atomic.get());
        }
    }
}
